<html>

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>一张图系统功能-geojson</title>
  <meta name="keywords" content="规划一张图" />
  <meta name="description" content="一张图系统" />
  <link rel="stylesheet" href="./resource/ol/ol.css">
  <script src="./resource/ol/ol.js"></script>
</head>

<body>
  <!-- 地图容器 -->
  <div id="map" class="map"></div>

  <script type="text/javascript">

    /** 创建要添加的图层**/
    // 创建图层：路网
    const MapLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        // 设置本地离线瓦片所在路径
        url: 'mapabc/roadmap' + '/{z}/{x}/{y}.png',
      }),
      name: '路网地图',
    });

    // 创建wms图层,图层颜色样式需要提前在geoserver中配置好sld
    const wmsSource = new ol.source.TileWMS({
      url: "http://localhost:8080/geoserver/libo1/wms",
      params: {
        format: 'image/png',
        layers: 'libo1: 淄博中心城区用海分类230524临淄区', // 图层的名称
        tiled: true,
        version: '1.3.0', // WMS服务版本号
        styles: '',
      },
      serverType: "geoserver",
    });
    
    const wmsLayer = new ol.layer.Tile({
      source: wmsSource,
      zIndex: 10
    });

    /**** 创建地图视图 ****/
    let centerPos = ol.proj.transform([117.96, 36.64], 'EPSG:4326', 'EPSG:3857');
    let zoom = 13;
    var view = new ol.View({
      center: centerPos, //地图中心位置
      zoom: zoom, //地图初始层级
      maxZoom: 18,
      minZoom: 1
    });

    //创建地图,把地图挂接到容器上
    let map = new ol.Map({
      target: 'map',
      layers: [MapLayer, wmsLayer],
      view: view,
    });

    // 点击图层显示属性
    map.on("singleclick",  (e) => {
      let viewResolution = map.getView().getResolution(); // 地图窗口分辨率
      // 获取到点击位置的wmslayer图层,获取图层上的数据源并调用源上面的方法 传入 坐标点 分辨率 投影 参数option
      let url = wmsLayer
        .getSource()
        .getFeatureInfoUrl(e.coordinate, viewResolution, "EPSG:4326", {
          // INFO_FORMAT: "text/html", 
          INFO_FORMAT: "application/json", //输出为json字符串
        });
        console.log(url);
      if(url) {
        fetch(url)
        .then((res) => res.json())
          .then((data) => {
            var features = new ol.format.GeoJSON().readFeatures(data);
            console.log(features);
          });
      }
    });

  </script>
</body>

</html>